package com.luych.toolbox.data.service.service;

import com.luych.toolbox.common.enums.DataRecoveryHistoryStatus;
import com.luych.toolbox.common.enums.DataRecoveryHistoryType;
import com.luych.toolbox.common.feign.intf.base.service.UserFeign;
import com.luych.toolbox.common.feign.param.data.service.DataRecoveryHistoryParam;
import com.luych.toolbox.common.feign.view.data.service.DataAgentView;
import com.luych.toolbox.common.feign.view.data.service.DataBackupHistoryView;
import com.luych.toolbox.common.feign.view.data.service.DataRecoveryHistoryView;
import com.luych.toolbox.common.feign.view.data.service.DataSourceView;
import com.luych.toolbox.common.page.PageParam;
import com.luych.toolbox.common.page.PageResult;
import com.luych.toolbox.common.service.base.BaseConvert;
import com.luych.toolbox.common.service.base.BaseService;
import com.luych.toolbox.common.service.exception.HttpException;
import com.luych.toolbox.common.service.page.SpringPageParamAdapter;
import com.luych.toolbox.common.service.page.SpringPageResultAdapter;
import com.luych.toolbox.data.service.constant.Constant;
import com.luych.toolbox.data.service.dao.DataAgentDao;
import com.luych.toolbox.data.service.dao.DataBackupHistoryDao;
import com.luych.toolbox.data.service.dao.DataRecoveryHistoryDao;
import com.luych.toolbox.data.service.dao.DataSourceDao;
import com.luych.toolbox.data.service.entity.DataAgent;
import com.luych.toolbox.data.service.entity.DataBackupHistory;
import com.luych.toolbox.data.service.entity.DataRecoveryHistory;
import com.luych.toolbox.data.service.entity.DataSource;
import com.luych.toolbox.data.service.job.DataRecoveryHistoryExecuteJob;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class DataRecoveryHistoryService
        extends BaseService<DataRecoveryHistoryView, DataRecoveryHistoryParam, DataRecoveryHistory>
        implements ApplicationListener<ApplicationReadyEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataRecoveryHistoryService.class);

    private static final BaseConvert<DataRecoveryHistoryParam, DataRecoveryHistory> dataRecoveryHistoryParamToEntity = DataRecoveryHistory::new;
    private static final BaseConvert<DataRecoveryHistory, DataRecoveryHistoryView> dataRecoveryHistoryEntityToView = DataRecoveryHistoryView::new;
    private static final BaseConvert<DataBackupHistory, DataBackupHistoryView> dataBackupHistoryEntityToView = DataBackupHistoryView::new;
    private static final BaseConvert<DataSource, DataSourceView> dataSourceEntityToView = DataSourceView::new;
    private static final BaseConvert<DataAgent, DataAgentView> dataAgentEntityToView = DataAgentView::new;

    private final Boolean rescheduleWhenStart;

    private final Scheduler scheduler;

    private final DataRecoveryHistoryDao dataRecoveryHistoryDao;
    private final DataBackupHistoryDao dataBackupHistoryDao;
    private final DataSourceDao dataSourceDao;
    private final DataAgentDao dataAgentDao;

    private final UserFeign userFeign;

    @Autowired
    public DataRecoveryHistoryService(@Value("${spring.quartz.rescheduleWhenStart:false}") Boolean rescheduleWhenStart,
                                      Scheduler scheduler,
                                      DataRecoveryHistoryDao dataRecoveryHistoryDao,
                                      DataBackupHistoryDao dataBackupHistoryDao,
                                      DataSourceDao dataSourceDao,
                                      DataAgentDao dataAgentDao,
                                      UserFeign userFeign) {
        super(dataRecoveryHistoryDao, dataRecoveryHistoryParamToEntity, dataRecoveryHistoryEntityToView);
        this.rescheduleWhenStart = rescheduleWhenStart;
        this.scheduler = scheduler;
        this.dataRecoveryHistoryDao = dataRecoveryHistoryDao;
        this.dataBackupHistoryDao = dataBackupHistoryDao;
        this.dataSourceDao = dataSourceDao;
        this.dataAgentDao = dataAgentDao;
        this.userFeign = userFeign;
    }

    private DataBackupHistoryView fill(DataBackupHistoryView view) {
        Optional<DataBackupHistory> dataBackupHistoryOpt = dataBackupHistoryDao.findById(view.getId());
        dataBackupHistoryOpt.map(DataBackupHistory::getDataSourceId).flatMap(dataSourceDao::findById).map(dataSourceEntityToView).ifPresent(view::setDataSource);
        dataBackupHistoryOpt.map(DataBackupHistory::getDataAgentId).flatMap(dataAgentDao::findById).map(dataAgentEntityToView).ifPresent(view::setDataAgent);
        dataBackupHistoryOpt.map(DataBackupHistory::getOwnerId).map(userFeign::get).ifPresent(view::setOwner);
        return view;
    }

    @Override
    protected DataRecoveryHistoryView fill(DataRecoveryHistoryView view) {
        Optional<DataRecoveryHistory> dataRecoveryHistoryOpt = dataRecoveryHistoryDao.findById(view.getId());
        dataRecoveryHistoryOpt.map(DataRecoveryHistory::getDataBackupHistoryId).flatMap(dataBackupHistoryDao::findById)
                .map(dataBackupHistoryEntityToView).map(this::fill).ifPresent(view::setDataBackupHistory);
        dataRecoveryHistoryOpt.map(DataRecoveryHistory::getOwnerId).map(userFeign::get).ifPresent(view::setOwner);
        return super.fill(view);
    }

    private void setStatus(String id, DataRecoveryHistoryStatus status) {
        DataRecoveryHistory dataRecoveryHistory = dataRecoveryHistoryDao.findById(id).orElseThrow(() ->
                new HttpException(HttpStatus.NOT_FOUND, Constant.DATA_BACKUP_PLAN_NOT_FOUND));
        dataRecoveryHistory.setStatus(status);
        dataRecoveryHistoryDao.save(dataRecoveryHistory);
    }

    private JobKey getJobKey(String id) {
        return new JobKey(id, DataRecoveryHistoryExecuteJob.class.getName());
    }

    private JobDetail getJobDetail(String id) {
        Map<String, Object> jobParam = new HashMap<String, Object>() {{
            this.put("id", id);
        }};
        return JobBuilder.newJob(DataRecoveryHistoryExecuteJob.class)
                .withIdentity(this.getJobKey(id))
                .usingJobData(new JobDataMap(jobParam))
                .build();
    }

    private Trigger getJobTrigger(String id) {
        return TriggerBuilder.newTrigger()
                .withIdentity(id, DataRecoveryHistoryExecuteJob.class.getName())
                .withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(1, 1))
                .build();
    }

    @Override
    public DataRecoveryHistoryView create(DataRecoveryHistoryParam param) {
        Assert.notNull(param.getDataBackupHistoryId(), "Param dataBackupHistoryId can't be empty");
        Assert.notNull(param.getName(), "Param name can't be empty");
        Assert.notNull(param.getOwnerId(), "Param ownerId can't be empty");

        // save
        DataRecoveryHistory dataRecoveryHistoryParam = dataRecoveryHistoryParamToEntity.apply(param);
        dataRecoveryHistoryParam.setType(DataRecoveryHistoryType.MANUAL);
        dataRecoveryHistoryParam.setStatus(DataRecoveryHistoryStatus.LOADING);
        DataRecoveryHistory dataRecoveryHistoryResult = dataRecoveryHistoryDao.save(dataRecoveryHistoryParam);
        DataRecoveryHistoryView view = this.fill(dataRecoveryHistoryEntityToView.apply(dataRecoveryHistoryResult));

        // backup
        try {
            scheduler.scheduleJob(this.getJobDetail(view.getId()), this.getJobTrigger(view.getId()));
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }

        return view;
    }

    @Override
    public DataRecoveryHistoryView modify(DataRecoveryHistoryParam param) {
        throw new HttpException(HttpStatus.METHOD_NOT_ALLOWED, Constant.DATA_RECOVERY_HISTORY_MODIFY_REJECT);
    }

    @Override
    public void remove(String id) {
        try {
            scheduler.deleteJob(this.getJobKey(id));
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }
        dataRecoveryHistoryDao.deleteById(id);
    }

    public PageResult<DataRecoveryHistoryView> pageByKeyword(PageParam pageParam, String keyword) {
        Page<DataRecoveryHistory> page;
        if (StringUtils.isEmpty(keyword)) {
            page = dataRecoveryHistoryDao.findAll(new SpringPageParamAdapter(pageParam));
        } else {
            page = dataRecoveryHistoryDao.findByNameLike("%" + keyword + "%", new SpringPageParamAdapter(pageParam));
        }
        PageResult<DataRecoveryHistory> pageResult = new SpringPageResultAdapter<>(page);
        return pageResult.convert(dataRecoveryHistoryEntityToView).convert(this::fill);
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (Boolean.TRUE.equals(rescheduleWhenStart)) {
            List<DataRecoveryHistoryStatus> statuses = Arrays.asList(DataRecoveryHistoryStatus.LOADING, DataRecoveryHistoryStatus.RUNNING);
            List<DataRecoveryHistory> dataRecoveryHistorys = dataRecoveryHistoryDao.findByStatusIn(statuses);
            for (DataRecoveryHistory dataRecoveryHistory : dataRecoveryHistorys) {
                try {
                    scheduler.deleteJob(this.getJobKey(dataRecoveryHistory.getId()));
                    scheduler.scheduleJob(this.getJobDetail(dataRecoveryHistory.getId()), this.getJobTrigger(dataRecoveryHistory.getId()));
                    this.setStatus(dataRecoveryHistory.getId(), DataRecoveryHistoryStatus.RUNNING);
                } catch (SchedulerException e) {
                    this.setStatus(dataRecoveryHistory.getId(), DataRecoveryHistoryStatus.EXCEPTION);
                    throw new IllegalStateException(e);
                }
            }
        }
    }
}
